import { Injectable, Logger } from '@nestjs/common'
import axios from 'axios'
import * as fs from 'fs'
import * as path from 'path'
import * as FormData from 'form-data'

/**
 * 插件市场服务，支持插件搜索、下载、上传
 */
@Injectable()
export class PluginMarketService {
  private readonly logger = new Logger('PluginMarketService')
  private readonly marketplaceUrl = 'https://marketplace.vuenode.com/api'

  /**
   * 搜索插件
   */
  async searchPlugins(query: string) {
    const response = await axios.get(`${this.marketplaceUrl}/plugins/search`, {
      params: { q: query },
    })
    return response.data
  }

  /**
   * 获取插件详情
   */
  async getPluginDetails(name: string) {
    const response = await axios.get(`${this.marketplaceUrl}/plugins/${name}`)
    return response.data
  }

  /**
   * 下载插件并保存到本地 plugins 目录
   */
  async downloadPlugin(name: string, version: string) {
    const response = await axios.get(`${this.marketplaceUrl}/plugins/${name}/download/${version}`, {
      responseType: 'stream',
    })
    const pluginsDir = path.join(__dirname, '../../../plugins')
    if (!fs.existsSync(pluginsDir)) fs.mkdirSync(pluginsDir, { recursive: true })
    const pluginPath = path.join(pluginsDir, `${name}-${version}.zip`)
    const writer = fs.createWriteStream(pluginPath)
    response.data.pipe(writer)
    return new Promise((resolve, reject) => {
      writer.on('finish', () => resolve(pluginPath))
      writer.on('error', reject)
    })
  }

  /**
   * 提交插件到市场（Buffer 或本地文件）
   * @param pluginData 插件元数据
   * @param zipFile Buffer 或本地文件路径
   */
  async submitPlugin(pluginData: any, zipFile: Buffer | string) {
    const formData = new FormData()
    formData.append('metadata', JSON.stringify(pluginData))
    if (Buffer.isBuffer(zipFile)) {
      formData.append('package', zipFile, {
        filename: 'plugin.zip',
        contentType: 'application/zip',
      })
    } else if (typeof zipFile === 'string') {
      // 本地文件路径
      formData.append('package', fs.createReadStream(zipFile), {
        filename: path.basename(zipFile),
        contentType: 'application/zip',
      })
    } else {
      throw new Error('zipFile 必须为 Buffer 或 文件路径')
    }

    const response = await axios.post(`${this.marketplaceUrl}/plugins/submit`, formData, {
      headers: {
        ...formData.getHeaders(),
        Authorization: `Bearer ${process.env.MARKETPLACE_API_KEY}`,
      },
      maxContentLength: Infinity,
      maxBodyLength: Infinity,
    })
    return response.data
  }
}
